package models;

import play.*;
import play.data.validation.Min;
import play.data.validation.Required;
import play.db.jpa.*;
import validation.Unique;

import javax.persistence.*;

import java.util.*;
/**
 * 角色（或代表一定的级别）
 * @author yujie
 */
@Entity 
public class JueSe extends Model  implements Comparable<JueSe>{
	/**
	 * 角色名称（非空，唯一）
	 */
	@Required
	@Unique(message = "JueSe.mingCheng.Unique")
    public String mingCheng;
	
	/**
	 * 级别（非空，唯一，正整数）
	 * 说明：在代码中并不设定具体角色，而是采用级别属性，级别高的权限就高，级别低的权限就低
	 */
	@Required
	@Min(0)
    public int jiBie;
	
	/**
	 * 权限集合：该角色所拥有的所有权限
	 * 单向映射关系：多个权限对应多个角色
	 */
	@ManyToMany
	public Set<QuanXian> quanXians = new HashSet();;
	
	@Override
	public String toString() {
		return mingCheng+"("+jiBie+")";
	}
	/**
	 * 添加权限
	 * @param qx
	 */
	public void jiaQuanXian(QuanXian qx){
		if(quanXians.contains(qx))	return;
		else{
			quanXians.add(qx);
			this.save();
		}
	}
	/**
	 * 批量添加权限
	 * @param qxs
	 */
	public void jiaQuanXian(Collection<QuanXian> qxs){
		quanXians.addAll(qxs);
		this.save();
	}
	/**
	 * 批量去除权限
	 * @param qxs
	 */
	public void quQuanXian(Collection<QuanXian> qxs){
		quanXians.removeAll(qxs);
		this.save();
	}
	/**
	 * 去除权限
	 * @param qx
	 */
	public void quQuanXian(QuanXian qx){
		if(quanXians.contains(qx)){
			quanXians.remove(qx);
			this.save();
		}
	}
	/**
	 * 获取等级相等或更低的角色列表
	 * @return
	 */
	public List<JueSe> keXuanJueSe(){
		List jueSes=new ArrayList<JueSe>();
		jueSes=JueSe.find("jiBie <= ? order by jiBie desc", jiBie).fetch();
		return jueSes;
	}
	public JueSe(String mingCheng, int jiBie) {
		super();
		this.mingCheng = mingCheng;
		this.jiBie = jiBie;
	}
	/* (non-Javadoc)
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(JueSe qiTa) {
		return this.jiBie-qiTa.jiBie;
	}
	
	
	
}
